package hot100;

import java.sql.SQLOutput;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;

public class Solution103 {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if (root == null) {
            return new LinkedList<>();
        }
        List<List<Integer>> ans = new LinkedList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        boolean isOrderLeft = true;
        queue.offer(root);
        while (!queue.isEmpty()) {
            LinkedList<Integer> cur = new LinkedList<>();
            while (!queue.isEmpty()) {
                int size = queue.size();
                for (int i = 0; i < size; i++) {
                    TreeNode top = queue.poll();
                    if (top.left != null) {
                        queue.offer(top.left);
                    }
                    if (top.right != null) {
                        queue.offer(top.right);
                    }
                    if (isOrderLeft) {
                        cur.addFirst(top.val);
                    } else {
                        cur.addLast(top.val);
                    }
                }
            }
            ans.add(cur);
            isOrderLeft = !isOrderLeft;
        }
        return ans;
    }
}
